package com.ludomancy.gamelib.entity;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;

import com.ludomancy.gamelib.Widget;
import com.ludomancy.gamelib.WorldScreenProjection;

public class WorldWidget extends Widget
{
	private World world;
	private Point selectedAnchor;
	private WorldScreenProjection projector;

	public WorldWidget(Widget parent, Rectangle area, World world)
	{
		super(parent, area);
		this.world = world;
		projector = new WorldScreenProjection(area.width, area.height, world.width, world.height);
	}
			
	public void paint(Graphics g)
	{
		world.paint(g, projector);
	}
	
	public void mouseDown(Point pos)
	{
		Entity e = world.getEntityAt(pos);
		if(e != null)
		{
			world.selected = e;
			selectedAnchor = new Point(e.pos.x - pos.x, e.pos.y - pos.y);
			e.onClick(new Point(pos.x - e.pos.x, pos.y - e.pos.y));
		}
		else
		{
			world.selected = null;
		}
	}
	
	public Object beginDrag(Point cursor)
	{
		Entity e = world.getEntityAt(cursor);
		if(e != null && e.isMovable())
		{
			world.onBeginDrag(e, new Point(cursor.x + selectedAnchor.x, cursor.y + selectedAnchor.y));
			return e;
		}
		return null;
	}
	
	public void onDrag(Point cursor, Object object)
	{
		if(object instanceof Entity)
		{
			Entity e = (Entity) object;
			Point desired = new Point(cursor.x + selectedAnchor.x, cursor.y + selectedAnchor.y);
			Point newpos = constrain(e, desired);
			world.onDrag(e, newpos);
		}
	}
	
	private Point constrain(Entity e, Point desired)
	{
		int x = Math.min(getWidth()-e.getWidth() - 2, Math.max(2, desired.x));
		int y = Math.min(getHeight()-e.getHeight() - 2, Math.max(2, desired.y));
		return new Point(x,y);
	}

	public void onDrop(Widget issuer, Point cursor, Object dragObject)
	{
		if(dragObject instanceof Entity)
		{
			Entity e = (Entity) dragObject;
			world.onEndDrag(e);
		}
	}

	public void mouseMoved(Point point)
	{
		Entity e = world.getEntityAt(point);
		if(e != null && e.isMovable())
		{
			world.hovering = e;
		}
		else
		{
			world.hovering = null;
		}
	}
}
